package ru.autofan.secure.aop;

import java.util.Set;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import ru.autofan.domain.AuthRole;
import ru.autofan.domain.Role;
import ru.autofan.secure.AuthRoleSupport;
import ru.autofan.secure.CurrentRolesHolder;
import ru.autofan.secure.Restricted;

public class RestrictedInterceptor implements MethodInterceptor {

	private CurrentRolesHolder currentRolesHolder;

	public CurrentRolesHolder getCurrentRolesHolder() {
		return currentRolesHolder;
	}

	public void setCurrentRolesHolder(CurrentRolesHolder currentRolesHolder) {
		this.currentRolesHolder = currentRolesHolder;
	}

	public RestrictedInterceptor() {
	}

	public Object invoke(MethodInvocation inv) throws Throwable {
		Restricted restricted = inv.getMethod().getAnnotation(Restricted.class);
		if (restricted != null) {
			AuthRoleSupport annotatedRole = restricted.authRoleSupport();
			Set<Role> currentRoles = getCurrentRolesHolder().getRoles();
			for (Role r : currentRoles) {
				if (r instanceof AuthRole
						&& !annotatedRole.isApplicable(AuthRoleSupport
								.valueOf(r.getType()))) {
					throw new SecurityException();
				}

			}
		}
		return inv.proceed();
	}

}
